import re

with open('input.txt') as file:
    lines = (line.strip() for line in file)
    rules = {}

    def build_re(rule: str):
        if "|" in rule:
            parts = rule.split(' | ')
            return '(?:' + '|'.join(f'(?:{build_re(x)})' for x in parts) + ')'
        if rule[0] == '"':
            return rule[1]
        if rule[-1] == '+':
            return build_re(rules[rule[:-1]]) + '+'
        return ''.join(build_re(rules[r]) for r in rule.split())

    for line in lines:
        if not line:
            break
        num, rule = line.split(': ')
        rules[num] = rule
    
    regex = build_re(rules['0'])

    count = 0
    for line in lines:
        if re.fullmatch(regex, line):
            count += 1
    
    print(count)